<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件上传</title>
  </head>
  <body>
    <h2>单文件上传</h2>
    <form id="uploadForm" action="" method="" enctype="">
      <input type="file" name="file" />
      <button type="submit">上传文件</button>
    </form>
    <script>
      const fileinput = document.querySelector('input[type="file"]')
      const uploadForm = document.getElementById('uploadForm')

      uploadForm.addEventListener('submit', function (event) {
        event.preventDefault() // 阻止表单默认提交行为
        const file = fileinput.files[0] // 待上传的文件
        if (file) {
          //  文件上传逻辑
          const xhr = new XMLHttpRequest()
          const formData = new FormData()
          formData.append('file', file)
          xhr.open('POST', '/your_upload_url', true)
          xhr.onreadystatechang = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
              document.getElementById('result').innerHTML = '上传完成！服务器返回：' + xhr.responseText
            }
          }
          xhr.send(formData)
        } else {
          alert('请选择文件')
        }
      })
    </script>
  </body>
</html>
